import React, {Component} from 'react';
import BaseComponent from "@/components/BaseComponent";
import {Button, Card, Col, Input, message, Popconfirm, Radio, Row} from 'antd';
import './list.less'
import {connect} from "dva";
import styled from 'styled-components';
import styles from "@/pages/Devices/monitor/list.less";
import StandardTable from '@/components/StandardTable';

import CreateView from "@/pages/Devices/monitor/Create";
import PreviewView from "@/pages/Devices/monitor/Preview";
import EditView from '@/pages/Devices/monitor/Edit';
import SsjkView from '@/pages/Devices/monitor/SsjkView';

const HeaderRight = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
`;

const MBtn = styled.a`
  color: #40a9ff;
  margin-left: 8px;
  margin-right: 8px;
`;

const MBtn2 = styled.a`
  color: red;
  margin-left: 8px;
  margin-right: 8px;
`;

@connect(({ monitorinfo, loading }) => ({
  data: monitorinfo.data,
  isLoading: loading.effects['monitorinfo/listAllmonitroInfo'],
  isCreating: loading.effects['monitorinfo/createNewMnitorinfo'],
  isUpdating: loading.effects['monitorinfo/updateLockInfo'],
  isDeling: loading.effects['monitorinfo/deleteById'],
}))

class Index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 待预览或编辑的监控列表数据
      record: {},
      // 被选中的rows
      selectedRowKeys: [],
      // 新增
      createVisible: false,
      // 预览
      previewVisible: false,
      // 编辑
      updateVisible: false,
      // 实时监控
      ssjk: false,
      // 搜索名称
      keyword:"",
    };
  }

  columns = [
    // {
    //   title: 'url',
    //   width: 150,
    //   dataIndex: 'url',
    // },
    {
      title: '企业名称',
      width: 140,
      dataIndex: 'enterpriseName',
    },
    {
      title: '法人代表',
      width: 130,
      dataIndex: 'frRepr',
    },
    {
      title: '联系方式',
      width: 130,
      dataIndex: 'phone',
    },
    {
      title: '地址',
      width: 140,
      dataIndex: 'address',
    },
    {
      title: '企业类型',
      width: 140,
      dataIndex: 'enterpriseType',
    },
    {
      title: '操作',
      width: 300,
      fixed: 'right',
      render: (text, record, index) => {
        return (
          <div className={styles.operate_col}>
            <MBtn
              onClick={() => {
                this.handlePreviewClick({ record });
              }}
            >
              详情
            </MBtn>
            <MBtn
              onClick={() => {
                this.handleEditClick({ record });
              }}
            >
              编辑
            </MBtn>
            <Popconfirm
              title="确定执行当前操作吗?"
              onConfirm={() => {
                this.handleDelClick({ record });
              }}
            >
              <MBtn>删除</MBtn>
            </Popconfirm>
            <MBtn2
              onClick={() => {
                this.handleSsjkClick();
              }}>
              <Button type="danger">实时监控</Button>
            </MBtn2>
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.listAllLockInfos()
    this.listAllLockInfosBy()
  }

  /**
   * 分页获取列表数据
   */
  listAllLockInfos = () => {
    this.listAllLockInfosBy({});
  }

  listAllLockInfosBy = (params) => {
    this.execHttp('monitorinfo/listAllmonitroInfo',{ currentPage: 1, pageSize: 10, ...params })
  };

  /**
   *搜索按钮被点击
   */
  handleSearchClick = () => {
    const { keyword } = this.state;
    this.listAllLockInfosBy({ keyword: keyword });
  };

  handleKeywordChange = e => {
    const {
      target: { value },
    } = e;
    this.setState({
      keyword: value,
    });
  };

  /**
   * 重置按钮被点击
   */
  handleResetClick = () => {
    this.setState({ keyword: '' }, () => {
      this.listAllLockInfosBy({});
    });
  };

  /**
   * 新建按钮被点击
   */
  handleShowCreateClick = () => {
    this.setState({
      createVisible: true,
    });
  };

  /**
   *新增关闭按钮被点击
   */
  handleCreateViewClose = e => {
    this.setState({
      createVisible: false,
    });
  };

  /**
   * 新增视图确认按钮被点击
   * @param data
   */
  handleCreateViewConfirmClick = ({ data }) => {
    // console.log(data)
    if (this.props.isCreating) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('monitorinfo/createNewMnitorinfo', { ...data })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          console.log("succes：",msg)
          this.successMessage(msg);
        } else {
          this.errorMessage('出错了');
        }
        this.setState({ createVisible: false }, () => {
          this.listAllLockInfos();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   * 获取包装后的数据
   * @param {*} msg
   * @returns
   */
  getPackMessage=(msg)=> {
    return <span style={{ color: '#333', fontSize: '15px', fontWeight: '600' }}>{msg}</span>;
  }

  /**
   * 显示成功信息
   * @param {*} msg
   */
  successMessage = (msg = '') => {
    const str = this.getPackMessage(msg);
    message.success(str);
  };

  /**
   * 显示错误信息
   * @param {*} msg
   */
  errorMessage = (msg) => {
    const str = this.getPackMessage(msg);
    message.error(str);
  };

  /**
   * 处理点击事件
   */
  handleOnSelectLocationClick = () => {
    this.setState({ locationSelectVisible: true });
  };

  /**
   * 处理点击事件
   */
  handleOnSelectBusinessCodeClick = () => {
    this.setState({ businessSelectVisible: true });
  };

  /**
   * 编辑按钮被点击
   * @param record
   */
  handleEditClick = ({ record }) => {
    this.setState({
      record: record,
      updateVisible: true,
    });
  };

  /**
   * 编辑视图确认按钮被点击
   * @param data
   */
  handleUpdateViewConfirmClick = ({ data }) => {
    if (this.props.isUpdating) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('monitorinfo/updateLockInfo', { ...data })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage(msg);
        }
        this.setState({ updateVisible: false }, () => {
          this.listAllLockInfosBy();
        });
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   *编辑关闭按钮被点击
   */
  handleUpdateViewClose = e => {
    this.setState({
      updateVisible: false,
    });
  };

  /**
   * 详情按钮被点击
   * @param record
   */
  handlePreviewClick = ({ record }) => {
    this.setState({
      record: record,
      previewVisible: true,
    });
  };

  /**
   * 删除按钮被点击
   * @param record
   */
  handleDelClick = ({ record }) => {
    this.deleteById({ id: record.id });
  };

  /**
   * 实时监控
   */
  handleSsjkClick = () =>{
    this.setState({
      ssjk:true
    })
  }

  /**
   * 执行删除任务
   * @param id
   */
  deleteById = ({ id }) => {
    if (this.props.isDeling) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('monitorinfo/deleteById', { id: id })
      .then(value => {
        hide();
        const {
          success,
          data: { msg },
        } = value;
        if (success) {
          this.successMessage(msg);
        } else {
          this.errorMessage(msg);
        }
        this.listAllLockInfosBy();
      })
      .catch(reason => {
        hide();
        this.errorMessage(reason);
      });
  };

  /**
   * table状态改变时调用
   * @param pagination
   * @param filtersArg
   * @param sorter
   */
  handleTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.listAllLockInfosBy(params);
  };

  render() {
    const { selectedRowKeys } = this.state;
    return (
      <div>
        <Card bordered={true}>
          <Row>
            <Col span={8}>
              <Button type="primary" style={{ marginRight: '8px' }} onClick={this.handleShowCreateClick}>新建</Button>
            </Col>
            <Col span={16}>
              <HeaderRight>
                <Input
                  value={this.state.keyword}
                  style={{ width: '200px', marginRight: '8px' }}
                  placeholder="请输入企业名称"
                  allowClear
                  onChange={this.handleKeywordChange}
                />
                <Button
                  type="primary"
                  style={{ marginRight: '8px' }}
                  onClick={this.handleSearchClick}
                >
                  搜索
                </Button>
                <Button type="default" onClick={this.handleResetClick}>
                  重置
                </Button>
              </HeaderRight>
            </Col>
          </Row>
        </Card>
        {/*列表*/}
        <Card bordered={true} style={{ marginTop: '16px' }}>
          <StandardTable
            data={this.props.data}
            hasSelection={false}
            selectedRows={selectedRowKeys}
            columns={this.columns}
            rowKey={'id'}
            loading={this.props.isLoading}
            onChange={this.handleTableChange}
            scroll={{ x: true }}
          />
        </Card>
        {/*新增*/}
        {this.state.createVisible ? (
          <CreateView
            wrappedComponentRef={createView => (this.createView = createView)}
            visible={this.state.createVisible}
            areaOptions={this.state.areaOptions}
            onClose={this.handleCreateViewClose}
            onConfirmClick={this.handleCreateViewConfirmClick}
            onSelectLocationClick={this.handleOnSelectLocationClick}
            onSelectBusinessCodeClick={this.handleOnSelectBusinessCodeClick}>
          </CreateView>
        ) : null}
        {/*预览*/}
        {this.state.previewVisible && Object.keys(this.state.record).length > 0 ? (
          <PreviewView
            visible={this.state.previewVisible}
            onClose={() => {
              this.setState({ previewVisible: false });
            }}
            record={this.state.record}
          ></PreviewView>
        ) : null}
        {/*编辑*/}
        {this.state.updateVisible && Object.keys(this.state.record).length > 0 ? (
          <EditView
            wrappedComponentRef={createView => (this.updateView = createView)}
            visible={this.state.updateVisible}
            areaOptions={this.state.areaOptions}
            record={this.state.record}
            onClose={this.handleUpdateViewClose}
            onConfirmClick={this.handleUpdateViewConfirmClick}
            onSelectLocationClick={this.handleOnSelectLocationClick}
            onSelectBusinessCodeClick={this.handleOnSelectBusinessCodeClick}
          ></EditView>
        ) : null}
        {/*实时监控*/}
        {this.state.ssjk && (
          <SsjkView
            visible={this.state.ssjk}
            onClose={() => {
              this.setState({ ssjk: false });
            }}
            // record={this.state.record}
          ></SsjkView>
        )}
      </div>
    );
  }
}



export default Index;
